package day12;

import java.util.Random;

/**
 * @author oldliu
 * @since 1.0
 */
//取钱人
public class Taker extends Thread {
    private final Accout ac;

    public Taker(String name, Accout ac) {
        super(name);
        this.ac = ac;
    }

    @Override
    public void run() {
        Random rd = new Random();


        while (ac.getMoney() > 0) {
            int rmb = rd.nextInt(100);
            System.out.println(this.getName() + "打算取钱：" + rmb + "元，当前余额是" + ac.getMoney() + "元");
            synchronized (ac) {
                if (ac.getMoney() >= rmb) {
                    try {
                        sleep((long) (500 * Math.random()));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    boolean ok = ac.withDraw(rmb);
                    System.out.println(this.getName() + "取钱" + rmb + "元" + (ok ? "成功" : "失败") + "，当前余额是" + ac.getMoney() + "元");
                } else {
                    System.out.println(this.getName() + "打算取钱：" + rmb + "元，当前余额是" + ac.getMoney() + "元,余额不足");
                }
            }

            try {
                sleep(400);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
